import { Component, OnInit, OnDestroy, Input, Output, ViewChild, ElementRef, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { WatchlistMiniService, WatchlistGroup } from "watchlist-mini";
import { UserService } from "user";
import * as _ from "lodash";

// 添加自选股按键状态
const STATUS = {
  ONEON: "ONE_ON",
  ONEOFF: "ONE_OFF",
  MULTION: "MULTI_ON",
  MULTIOFF: "MULTI_OFF",
};

@Component({
  selector: 'mini-addstock',
  templateUrl: 'mini-addstock.component.html',
  styleUrls: ['mini-addstock.component.less'],
})
export class MiniAddStockComponent implements OnInit, OnDestroy {
  @Input() stockSource: Observable<any>;
  @Input() placement: string;
  @ViewChild("addWLBtn1", { read: ElementRef }) addBtn1: ElementRef;
  @ViewChild("addWLBtn2", { read: ElementRef }) addBtn2: ElementRef;
  currentSymbol: string;
  allWatchlistGroups: WatchlistGroup[] = [];
  groupLists: WatchlistGroup[] = undefined;
  initCheckedList: string[];  // 已经包含了该自选股的分组id列表
  initUncheckedList: string[];  // 未包含该自选股的分组id列表
  actionSub = new Subject();
  subscription: Subscription;
  // 是否显示列表
  showAddStockModal = false;
  wlgroupLenth: number = 0;
  symbolSource = new Subject();
  // 定位自选股分组的弹框位置
  placeTop: number;
  placeRight: number;
  allst = STATUS;
  btnStatus = STATUS.ONEON;

  constructor(private wls: WatchlistMiniService, private us: UserService) { 
    this.wls.emptyGroupOfAddStockSub.subscribe(_ => {
      this.wls.addGroupSymbols(this.groupLists[0], [this.currentSymbol]);
    });
   }

  ngOnInit() {
    // 获取自选股分组的状态
    this.subscription = Observable.combineLatest(
      this.wls.rawGroupsSub,
      this.stockSource,
      (allGroups: Array<any>, stock, toggle) => {
        // console.log('symbolSubscription stock:', stock);
        // console.log('symbolSubscription allGroups:', allGroups);
        this.allWatchlistGroups = allGroups;
        this.wlgroupLenth = allGroups.length;
        if (!stock || !this.wlgroupLenth) return false;
        return stock;
      }).subscribe(res => {
        if (!res) {
          this.btnStatus = STATUS.ONEON;
          return false;
        }

        let tempList = [];
        let tempCheckList = [];
        this.allWatchlistGroups.map((g: WatchlistGroup) => {
          this.currentSymbol = res['symbol'];
          let checked = false;
          for ( let i = 0 ; i < g.stocks.length ; i ++ ) {
            if ( g.stocks[i].symbol ===  res['symbol'] ) {
              checked = true;
            }
          }
          if (checked) {
            tempCheckList.push(g.groupId);
          }
          tempList.push(_.merge({}, g, { checked }));
        });

        // 设定自选按键状态
        // this.btnStatus = this.wlgroupLenth > 1 ? STATUS.MULTI : (tempCheckList.length ? STATUS.ONEOFF : STATUS.ONEON);
        if (this.wlgroupLenth > 1) {
          this.btnStatus = tempCheckList.length ? STATUS.MULTIOFF : STATUS.MULTION;
        } else {
          this.btnStatus = tempCheckList.length ? STATUS.ONEOFF : STATUS.ONEON;
        }
        this.groupLists = [...tempList];
        this.initCheckedList = [...tempCheckList];
        // console.log('btnStatus:', this.btnStatus);
        // console.log('groupLists:', this.groupLists);
        // console.log('initCheckedList:', this.initCheckedList);
      });

    // 添加或者移除当前自选股
    this.subscription.add(this.actionSub
      // .debounceTime(100)
      .subscribe(_ => {
        // 计算需要删除的分组
        this.groupLists.map(g => {
          // 新增关注
          if (g["checked"]) {
            if (this.initCheckedList.indexOf(g.groupId) === -1) {
              // console.log('confirm add to group:', g);
              this.wls.addGroupSymbols(g, [this.currentSymbol]);
            }
          } else {
            // 取消关注
            if (this.initCheckedList.indexOf(g.groupId) !== -1) {
              // console.log('confirm delete from group:', g);
              this.wls.deleteGroupSymbols(g, [this.currentSymbol]);
            }
          }
          console.log('check status:', g['checked']);
        });
      }));
  }

  ngOnDestroy() {
    this.subscription ? this.subscription.unsubscribe() : null;
  }

  // 单个自选股分组的添加和移除操作
  toggleOneGroup(action: string) {
    // console.debug('toggleOneGroup: ', action);
    // 未登录
    if (!this.us.isLogined) {
      return this.us.setModal("login");
    }
    // 无分组可添加
    if (!this.wlgroupLenth) {
      this.wls.isAddStock = true;
      return this.wls.emptyGroupSub.next();
    }
    switch (action) {
      case "add":
        this.wls.addGroupSymbols(this.groupLists[0], [this.currentSymbol]);
        break;
      case "remove":
        this.wls.deleteGroupSymbols(this.groupLists[0], [this.currentSymbol]);
        break;
    }
  };

  // 需要设定right值的位置;
  placeArray = ["vtrade", "live"]; // liveinline, default
  // 打开或关闭自选股分组列表
  toggleGroupList(type: string) {
    if (!this.us.isLogined) {
      return this.us.setModal("login");
    }

    if (this.showAddStockModal) {
      this.showAddStockModal = false;
    } else {
      this.showAddStockModal = true;
      // console.debug('this.placement: ', this.placement);
      if (this.placeArray.indexOf(this.placement) !== -1) {
        let el = type === 'btn1' ? this.addBtn1.nativeElement : this.addBtn2.nativeElement;
        let t = el.getBoundingClientRect().bottom;
        let r = el.getBoundingClientRect().right;
        this.placeTop = t + 10;
        this.placeRight = document.querySelector('body').offsetWidth - r - 10;
      }
    }
  }

  // 点击后马上更新到自选股分组
  updateGroupNow(group) {
    this.actionSub.next();
    this.closeModal();
  }

  closeModal() {
    this.showAddStockModal = false;
  }

  disBubble(e: MouseEvent) {
    e.stopPropagation();
  }
}